package com.lhy.admin.web;

import com.lhy.admin.common.secure.authorization.Logical;
import com.lhy.admin.common.secure.authorization.Permissions;
import com.lhy.admin.common.treeable.Treeable;
import com.lhy.admin.common.treeable.TreeableUtil;
import com.lhy.admin.model.Department;
import com.lhy.admin.model.extend.DepartmentTree;
import com.lhy.admin.service.DepartmentService;
import com.lhy.commonweb.model.ResponseResult;
import com.lhy.commonweb.service.AbstractService;
import com.lhy.commonweb.web.BaseControllerImpl;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("department")
@Permissions
public class DepartmentController extends BaseControllerImpl<Department, Integer> {

    public DepartmentController(@Qualifier("departmentService") AbstractService service) {
        super(service);
    }

    /**
     *部门树接口，需要department.view部门查询权限
     **/
    @Permissions(value = "department.view",logical = Logical.AND)
    @RequestMapping(value = "tree", method = RequestMethod.GET)
    public List<Treeable> tree(@Validated @ModelAttribute Department bean) {
        List<Department> departments = super.queryCond(bean);
        return TreeableUtil.toTree(departments, DepartmentTree.class);
    }

    @Override
    @Permissions("department.view")
    public Department get(@PathVariable("id") Integer id) {
        return super.get(id);
    }

    @Override
    @Permissions("department.add")
    public ResponseResult create(@RequestBody Department bean) {
        return ResponseResult.create(DepartmentService.class.cast(service).createDepartment(bean));
    }


    @Override
    @Permissions("department.edit")
    public ResponseResult update(@RequestBody Department bean) {
        if (bean.getParent() == null) {
            bean.setParent(0);
        }
        return super.update(bean.setUpdated(new Date()));
    }

    @Override
    @Permissions("department.del")
    public ResponseResult delete(@PathVariable("id") Integer id) {
        return ResponseResult.create(DepartmentService.class.cast(service).delDepartment(id));
    }
}
